<?php


namespace app\common\business;


use app\common\business\SpecsValue as SpecsValueBiz;

class Goods
{
    public $goodsModel = null;

    public function __construct() {
        //初始化模型对象
        $this->goodsModel = new \app\common\model\mysql\Goods();
    }

    public function getLists($field, $where, $num = 5) {
        try {
            $list = $this->goodsModel->getLists($field, $where, $num);
            $result = $list;
        }catch (\Exception $e) {
            // 最好这个地方的结构可以写到基础类库中
            return [];
        }
        return $result;
    }

    public function insertData($data) {
        // 开启一个事务
        $this->goodsModel->startTrans();
        try {
            if (empty($data)) {
                return false;
            }
            //添加商品基本信息  返回主键ID
            $goodsId = $this->goodsModel->addReturnId($data);
            if (!$goodsId) {
                throw new \think\Exception("添加商品失败");
            }
            //统一规格和多规格都插入到sku表  查询详情时  直接以sku ID查询
            if ($data['goods_specs_type'] == 1) {
                //统一规格
                $data['goods_id'] = $goodsId;
                $res = (new GoodsSku())->save($data);
                if ($res) {
                    $goodsUpdateData = [
                        "sku_id" => $res,
                    ];
                    // 执行完毕之后 更新 主表中的数据哦。
                    $goodsRes = $this->goodsModel->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw  new \think\Exception("insertData:goods主表更新失败");
                    }
                } else {
                    throw new \think\Exception("sku表新增失败");
                }
                $this->goodsModel->commit();
                return true;
            } else if ($data['goods_specs_type'] == 2) {
                //多规格
                $data['goods_id'] = $goodsId;
                $res = (new GoodsSku())->saveAll($data);
                if (!empty($res)) {
                    //添加成功 计算库存
                    $stock = array_sum(array_column($res, "stock"));
                    $goodsUpdateData = [
                        "price" => $res[0]['price'],
                        "cost_price" => $res[0]['cost_price'],
                        "stock" => $stock,
                        "sku_id" => $res[0]['id'],
                    ];
                    // 执行完毕之后 更新 主表中的数据哦。
                    $goodsRes = $this->goodsModel->updateById($goodsId, $goodsUpdateData);
                    if (!$goodsRes) {
                        throw  new \think\Exception("insertData:goods主表更新失败");
                    }
                } else {
                    throw new \think\Exception("sku表新增失败");
                }
            }
            // 事务提交
            $this->goodsModel->commit();
            return true;
        } catch (\Exception $e) {
            // 事务回滚
            $this->goodsModel->rollback();
            return false;
        }

    }

    /**
     * 获取商品基本信息
     * @param $id
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getById($id) {
        return $this->goodsModel->find($id);
    }

    /**
     * 排序
     * @param $id
     * @param $listorder
     * @return array|bool|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function listorder($id, $listorder) {
        // 查询 id这条数据是否存在
        $res = $this->getById($id);
        if(!$res) {
            throw new \think\Exception("不存在该条记录");
        }
        $data = [
            "list_order" => $listorder,
        ];

        try {
            $res = $this->goodsModel->updateById($id, $data);
        }catch (\Exception $e) {
            // 记得记录日志。
            return false;
        }
        return $res;
    }

    /**
     * 更改状态
     * @param $id
     * @param $status
     * @return array|bool|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommendStatus($id, $status) {
        // 查询 id这条数据是否存在
        $res = $this->getById($id);
        if(!$res) {
            throw new \think\Exception("不存在该条记录");
        }
        if($res['is_index_recommend'] == $status) {
            throw new \think\Exception("状态修改前和修改后一样没有任何意义哦");
        }

        $data = [
            "is_index_recommend" => intval($status),
        ];

        try {
            $res = $this->goodsModel->updateById($id, $data);
        }catch (\Exception $e) {
            // 记得记录日志。
            return false;
        }
        return $res;
    }


    public function status($id, $status) {
        // 查询 id这条数据是否存在
        $res = $this->getById($id);
        if(!$res) {
            throw new \think\Exception("不存在该条记录");
        }
        if($res['status'] == $status) {
            throw new \think\Exception("状态修改前和修改后一样没有任何意义哦");
        }

        $data = [
            "status" => intval($status),
        ];

        try {
            $res = $this->goodsModel->updateById($id, $data);
        }catch (\Exception $e) {
            // 记得记录日志。
            return false;
        }
        return $res;
    }

    public function delete($id) {
        $res = $this->getById($id);
        if(!$res) {
            throw new \think\Exception("不存在该条记录");
        }
        return $this->goodsModel->where('id', $id)->delete();
    }

    /******************* API 接口 **********************/
    /**
     * 获取轮播图
     * @param int $num
     * @return array
     */
    public function getRotationChart($num = 5) {
        $where = [
            ['status', '=', 1],
            ['is_index_recommend', '=', 1],
            ['stock', '>', 0]
        ];
        try {
            $res = $this->goodsModel->getRotationChart($where, $num);
            $result = $res->toArray();
        } catch (\Exception $e) {
            return [];
        }
        return $result;

    }

    /**
     * 获取分类下的商品
     * @param $categoryId
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsByCategoryId($categoryId, $limit) {
        if (!$categoryId) {
            return [];
        }
        //获取子分类
        $cats = (new \app\common\model\mysql\Category())->getChildrenIds($categoryId);
        array_push($cats, $categoryId);

        //获取商品
        $res = $this->goodsModel->getGoodsByCategoryIds($cats, $limit);
        if ($res) {
            return $res->toArray();
        } else {
            return [];
        }
    }


    public function getDetailBySkuId($skuId) {
        //获取sku表信息和商品信息
        $skuBiz = new GoodsSku();
        $goodsSku = $skuBiz->getNormalSkuAndGoods($skuId);
        //获取商品的所有sku信息
        if(!$goodsSku) {
            return [];
        }
        if(empty($goodsSku['goods'])) {
            return [];
        }
        $goods = $goodsSku['goods'];
        $skus = $skuBiz->getSkusByGoodsId($goods['id']);
        if(!$skus) {
            return [];
        }
        //获得选中的属性ID
        $flagValue = "";    // 28,23
        foreach($skus as $sv) {
            if($sv['id'] == $skuId) {
                $flagValue = $sv["specs_value_ids"];
            }
        }
        //获取所有sku的属性
        //ID[
        //  "27,33" => 146
        //  "27,34" => 147
        //  "28,33" => 148
        //  "28,34" => 149
        //]
        $gids = array_column($skus, "id", "specs_value_ids");
        if($goods['goods_specs_type'] == 1) {   // 统一规格
            $sku = [];
        } else {    // 多规格
            $sku = (new SpecsValueBiz())->dealGoodsSkus($gids, $flagValue);
        }
        $result = [
            "id" => $skuId,
            "title" => $goods['title'],
            "promotion_title" => $goods['promotion_title'],
            "price" => $goodsSku['price'],
            "cost_price" => $goodsSku['cost_price'],
            "sales_count" => 0,
            "stock" => $goodsSku['stock'],
            "gids" => $gids,
            "image" => $goods['carousel_image'],
            "sku" => $sku,
            "detail" => [
                "d1" => [
                    "商品编码" => $goodsSku['id'],
                    "上架时间" => $goods['create_time'],
                ],
                "d2" => preg_replace('/(<img.+?src=")(.*?)/', '$1'.request()->domain().'$2',$goods['description']),
            ],

        ];

        return $result;
    }

    public function getGoodsContent($skuId) {
        //获取sku表信息和商品信息
        //获取商品ID
        $res = (new \app\common\model\mysql\GoodsSku())->where('id', $skuId)->find();
        $res = $res->toArray();
        $goods = $this->goodsModel->getNormalGoods($res['goods_id']);
        if($goods) {
            $goods = $goods->toArray();
            $goods['description'] = preg_replace('/(<img.+?src=")(.*?)/', '$1'.request()->domain().'$2',$goods['description']);
            return $goods;

        }
        return [];
    }
}